import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_1800/pages/goods/GoodsDetail.dart';
import 'package:flutter_1800/pages/widgets/MyText.dart';
import 'package:flutter_1800/service/api_service.dart';
import 'package:flutter_1800/tools/AppUtil.dart';
import 'package:flutter_1800/tools/config.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class HomeTabViewPage extends StatefulWidget {
  Function gotoTab;

  HomeTabViewPage(this.gotoTab, {Key? key}) : super(key: key);

  @override
  _HomeTabViewPageState createState() => _HomeTabViewPageState();
}

class _HomeTabViewPageState extends State<HomeTabViewPage>
    with AutomaticKeepAliveClientMixin, RouteAware {
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  List banner = [];
  List tabs = [];
  Map? selectTab;
  List cates = [];

  @override
  void initState() {
    super.initState();
    queryData();
  }

  @override
  bool get wantKeepAlive => true;

  //回到当前页面
  @override
  void didPopNext() {
    queryData();
  }

  @override
  void didPop() {
    queryData();
  }

  void queryData() {
    ApiService.indexData().then((value) {
      setState(() {
        tabs = value["tabs"];
        selectTab = tabs[0];
        cates = selectTab!["children"];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    double screenWidth = MediaQuery.of(context).size.width;
    double gap = 10;
    int columns = 2;

    double itemWidth =
        (screenWidth - AppUtil.getPadding() * 2 - gap * (columns - 1)) /
            columns;
    double itemHeight = itemWidth + 80;

    return Scaffold(
        appBar: AppBar(
          shadowColor: Colors.transparent,
          centerTitle: true,
          elevation: 0.0,
          toolbarHeight: 40,
          title: MyText(
            "首页",
            weight: FontWeight.bold,
          ),
        ),
        backgroundColor: AppConfig.grayBgColor,
        body: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            child: Column(
              children: [
                Container(
                  margin: AppUtil.getCommonPadding(),
                  child: Column(
                    children: cates.map((e) {
                      List goodsList = e["list"];
                      return Column(
                        children: [
                          MyText(
                            e["name"].toString(),
                            fontSize: 18,
                            weight: FontWeight.bold,
                          ),
                          GridView.builder(
                            shrinkWrap: true,
                            physics: const NeverScrollableScrollPhysics(),
                            padding: const EdgeInsets.only(
                              top: 10,
                            ),
                            gridDelegate:
                                SliverGridDelegateWithFixedCrossAxisCount(
                              crossAxisCount: columns,
                              mainAxisSpacing: gap,
                              crossAxisSpacing: gap,
                              childAspectRatio: itemWidth / itemHeight,
                            ),
                            itemBuilder: (context, index) {
                              Map goods = goodsList[index];
                              return GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  AppUtil.getTo(GoodsDetail(goods["id"]));
                                },
                                child: Container(
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius:
                                            BorderRadius.circular(10)),
                                    child: Column(
                                      children: [
                                        AspectRatio(
                                          aspectRatio: 1 / 1,
                                          child: ClipRRect(
                                            borderRadius:
                                                BorderRadius.circular(4),
                                            child: goods["image"] == null
                                                ? Image.asset(
                                                    "images/noimage.png",
                                                    fit: BoxFit.cover,
                                                  )
                                                : CachedNetworkImage(
                                                    imageUrl: goods["image"],
                                                    fit: BoxFit.cover,
                                                  ),
                                          ),
                                        ),
                                        const SizedBox(height: 5),
                                        Container(
                                          padding: const EdgeInsets.all(5),
                                          child: Column(
                                            children: [
                                              Container(
                                                height: 30,
                                                alignment: Alignment.topLeft,
                                                child: MyText(
                                                  goods["title"],
                                                  color: AppConfig.font2,
                                                  fontSize: 14,
                                                  maxLines: 2,
                                                  textAlign: TextAlign.left,
                                                ),
                                              ),
                                              const SizedBox(height: 12),
                                              Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment
                                                        .spaceBetween,
                                                children: [
                                                  Row(
                                                    children: [
                                                      MyText(
                                                        "¥",
                                                        color: Colors.red,
                                                        fontSize: 12,
                                                      ),
                                                      MyText(
                                                        goods["minprice"]
                                                            .toString(),
                                                        color: Colors.red,
                                                        fontSize: 15,
                                                        weight: FontWeight.bold,
                                                      ),
                                                    ],
                                                  ),
                                                ],
                                              )
                                            ],
                                          ),
                                        )
                                      ],
                                    )),
                              );
                            },
                            itemCount: goodsList.length,
                          )
                        ],
                      );
                    }).toList(),
                  ),
                ),
              ],
            )));
  }
}
